﻿using AutoMapper;
using B.S.BaseData.Domain.Base;
using B.S.BaseData.Domain.Interfaces;
using B.S.BaseData.Domain.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ReadAPI.Applications.Commands.Departments;
using B.S.BaseData.ReadAPI.DTOs.ResponseDto;
using CSRedis;
using MediatR;

namespace B.S.BaseData.ReadAPI.Applications.CommandHandler.Departments
{
	public class GetdepartmentListCommandHandler : IRequestHandler<GetdepartmentListCommand, ApiResult<APIPaging<DepartmentDTO>>>
	{
		IBaseRepository<Department> depRep;
		IBaseRepository<UserInfo> userRep;
		IMapper mapper;

		public GetdepartmentListCommandHandler( IBaseRepository<Department> depRep, IMapper mapper, IBaseRepository<UserInfo> userRep)
		{
			this.depRep = depRep;
			this.mapper = mapper;
			this.userRep = userRep;
		}
		public async Task<ApiResult<APIPaging<DepartmentDTO>>> Handle(GetdepartmentListCommand request, CancellationToken cancellationToken)
		{
			try
			{
				var result = depRep.GetAllAsync(a => !a.IsDelete);
				if (!string.IsNullOrEmpty(request.DepartmentName))
				{
                    result = result.Where(a => a.DepartmentName.Contains(request.DepartmentName));
				}
				//总条数
				int total = result.Count();
				//总页数
				int pagecount = (int)Math.Ceiling(total * 1.0 / request.PageSize);
				//当前页数据
				result= result.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
				//映射
				List<DepartmentDTO> depDto = mapper.Map<List<DepartmentDTO>>(result);
				foreach (var item in depDto)
				{
					item.UserCount = userRep.GetAllAsync(a => a.DepartmentId == item.DepartmentId).Count();
					item.ManageName = (await userRep.GetAsync(a => a.UserId == item.ManageUser)).NickName;
				}
                var apiResult = new APIPaging<DepartmentDTO>()
                {
                    TotalCount = total,
                    PageCount = pagecount,
                    PageData = depDto
                };
				return ApiResult<APIPaging<DepartmentDTO>>.Success(apiResult, StatusCodeEnum.Ok);

			}
			catch (Exception)
			{

				throw;
			}
		}
	}
}
